import redis


class RedisConn:
    def __init__(self) -> None:
        self.r = redis.Redis()

    # 字符串添加
    def str_add(self, key, value, time=0):
        if time == 0:
            self.r.set(key, value)
        else:
            self.r.setex(key, time, value)

    # 字符串获取
    def str_get(self, key):
        value = self.r.get(key)
        if value:
            value = value.decode()
        return value

    # # 字符串删除
    def str_del(self, key):
        return self.r.delete(key)

    # hash类型封装
    # 添加
    def hash_add(self,key,params,value):
        self.r.hset(key,params,value)

    # 获取所有
    def getall_hash(self,key):
        return self.r.hgetall(key)

    # 获取单个
    def getone_hash(self,key,params):
        return self.r.hget(key,params)

    # 模糊查询
    def getvalues(self,key):
        getlist = []
        values = self.r.keys(key)
        if values:
            for i in values:
                getlist.append(i.decode())
        return getlist

    # 删除
    def del_hash(self,key,params):
        return self.r.hdel(key,params)

    # 判断key是否存在
    def findkey_hash(self,key):
        return self.r.exists(key)

    # 购物车加减
    def jiajian_hash(self,key,params,count,type):
        # 1为加   2为减
        if int(type) == 1:
            return self.r.hincrby(key,params,count)
        else:
            # 获取数量，如果数量大于1执行，如果小于等于1，提醒不能在减了
            number = self.getone_hash(key,"number")
            if number:
                number = number.decode()
                if int(number) > 1:
                    return self.r.hincrby(key,params,-count)
            return False


r = RedisConn()







